<template>
  <el-card class="upload-card">
    <el-tabs v-model="activeTab">
      <div class="space-select">
        <span>上传至：</span>
        <el-select v-model="activeSpaceId" placeholder="请选择空间">
          <el-option label="公共图库" value="null" />
          <el-option
            v-for="item in spaces"
            :key="item.id"
            :label="item.spaceName"
            :value="item.id"
          />
        </el-select>
      </div>
      <el-tab-pane label="本地图片上传" name="local">
        <el-form :model="localForm" label-width="80px" class="upload-form">
          <el-form-item label="图片名称">
            <el-input v-model="localForm.name" placeholder="请输入图片名称" />
          </el-form-item>
          <el-form-item label="图片介绍">
            <el-input v-model="localForm.introduction" placeholder="请输入图片介绍" />
          </el-form-item>
          <el-form-item label="图片分类">
            <el-select v-model="localForm.classifyId" placeholder="请选择图片分类">
              <el-option
                v-for="item in classifyStore.classifies"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图片标签">
            <el-select
              v-model="localForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签"
            />
          </el-form-item>
          <el-form-item label="图片文件">
            <el-upload
              drag
              :auto-upload="false"
              :show-file-list="true"
              :on-change="handleFileChange"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitLocal">上传</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="URL图片上传" name="url">
        <el-form :model="urlForm" label-width="80px" class="upload-form">
          <el-form-item label="图片名称">
            <el-input v-model="urlForm.picName" placeholder="请输入图片名称" />
          </el-form-item>
          <el-form-item label="图片介绍">
            <el-input v-model="urlForm.introduction" placeholder="请输入图片介绍" />
          </el-form-item>
          <el-form-item label="图片分类">
            <el-select v-model="urlForm.classifyId" placeholder="请选择图片分类">
              <el-option
                v-for="item in classifyStore.classifies"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图片标签">
            <el-select
              v-model="urlForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签"
            />
          </el-form-item>
          <el-form-item label="图片URL">
            <el-input v-model="urlForm.fileUrl" placeholder="请输入图片URL（推荐使用bing搜索）" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitUrl">上传</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadPictureAPI, uploadPictureByUrlAPI } from '@/api/pictureAPI'
import { listSpaceByUserIdAPI } from '@/api/spaceAPI'
import { useRoute } from 'vue-router'
import { useClassifyStore } from '@/stores/classify'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const classifyStore = useClassifyStore()

const route = useRoute()

console.log('route' + route.query.spaceId)

const activeTab = ref('local')

const activeSpaceId = ref(null)

const localForm = ref({
  name: '',
  introduction: '',
  classifyId: null,
  tags: [],
  file: null,
})

const urlForm = ref({
  picName: '',
  introduction: '',
  classifyId: null,
  tags: [],
  fileUrl: '',
})

const spaces = ref([])

//获取用户空间
const getSpaceById = async () => {
  const userId = userStore.userInfo.id || null
  console.log('获取用户空间:', userId)

  if (!userId) return
  const res = await listSpaceByUserIdAPI(userId)
  console.log('获取用户空间:', res)
  spaces.value = res.data
}

function handleFileChange(file) {
  localForm.value.file = file.raw
}

async function submitLocal() {
  // 简单交互逻辑
  if (!localForm.value.file) {
    ElMessage.error('请上传图片文件')
    return
  }
  console.log('提交本地图片表单:', localForm.value)
  uploadPictureAPI(localForm.value.file, {
    name: localForm.value.name,
    introduction: localForm.value.introduction,
    classifyId: localForm.value.classifyId,
    tags: localForm.value.tags,
    spaceId: route.query.spaceId || activeSpaceId.value,
  })
    .then(() => {
      ElMessage.success('本地图片上传成功')
      localForm.value = {
        name: '',
        introduction: '',
        classifyId: null,
        tags: [],
        file: null,
      }
    })
    .catch(() => {
      ElMessage.error('本地图片上传失败')
    })
}

function submitUrl() {
  if (!urlForm.value.fileUrl) {
    ElMessage.error('请输入图片URL')
    return
  }
  uploadPictureByUrlAPI({
    ...urlForm.value,
    spaceId: route.query.spaceId || activeSpaceId.value,
  })
    .then(() => {
      ElMessage.success('URL图片上传成功')
      urlForm.value = {
        picName: '',
        introduction: '',
        classifyId: null,
        tags: [],
        fileUrl: '',
      }
    })
    .catch(() => {
      ElMessage.error('URL图片上传失败')
    })
}

onMounted(() => {
  getSpaceById()
})
</script>

<style scoped>
.upload-card {
  max-width: 700px;
  margin: 40px auto;
  padding: 30px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
  background: #fff;
}
.upload-form {
  margin-top: 20px;
}
.el-upload {
  width: 100%;
}
.space-select {
  width: 100%;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.space-select span {
  width: 80px;
  text-align: right;
  color: #606266;
  font-size: 14px;
}
.space-select .el-select {
  flex: 1;
}
</style>
